import api from '../../api';
import { apiModeUtils } from '../../apiConfig';
import type { User, Role, Permission, Department, Team } from '../../../types/rbac';
import type { TenantLoginRequest } from '../../../types/tenant';

/**
 * 系统登录请求参数
 */
export interface SystemLoginRequest {
  username: string;                // 用户名
  password: string;                // 密码
  captcha?: string;                // 验证码
  rememberMe?: boolean;            // 记住登录
}

/**
 * 认证登录响应 - 匹配后端实际返回结构
 */
export interface AuthLoginResponse {
  // 用户基本信息（扁平化结构）
  userId: string;
  username: string;
  email: string;
  phone?: string;
  avatar?: string;
  gender?: number;
  age?: number;
  status: number;
  departmentId?: string;
  description?: string;
  superAdmin?: number | null;  // 后端返回的是 superAdmin，不是 isSuperAdmin
  permissions?: string[] | null;
  roleIds?: string[] | null;   // 后端返回的是 roleIds，不是 roles 对象数组
  
  // 令牌信息
  accessToken: string;
  refreshToken?: string;
  tokenType?: string;
  expiresIn?: string;
  loginTime?: string;
  message?: string | null;
}

/**
 * 刷新令牌请求参数
 */
export interface RefreshTokenRequest {
  refreshToken: string;            // 刷新令牌
}

// 导出租户登录请求类型（重新导出以保持兼容性）
export type { TenantLoginRequest };

/**
 * 认证API服务 - 使用优化的API包装器
 * 支持系统用户和租户用户，统一通过后端 system 模块处理认证和权限管理
 */

// 创建认证API包装器
const api_auth = apiModeUtils.createApi('authApi', api, false);

export const authApi = {
  // ===== 系统认证 API =====
  
  /**
   * 系统用户登录
   */
  systemLogin: (data: SystemLoginRequest): Promise<AuthLoginResponse> => {
    return api_auth.post('systemLogin', '/system/api/v3/sys/auth/login', data);
  },

  /**
   * 租户用户登录
   */
  tenantLogin: (data: TenantLoginRequest): Promise<AuthLoginResponse> => {
    return api_auth.post('tenantLogin', '/system/api/v3/tenant/auth/login', data);
  },

  /**
   * 用户登出
   */
  logout: (): Promise<void> => {
    return api_auth.post('logout', '/system/api/v3/sys/auth/logout');
  },

  /**
   * 租户用户登出
   */
  tenantLogout: (tenantCode: string): Promise<void> => {
    return api_auth.post('tenantLogout', '/system/api/v3/tenant/auth/logout', { tenantCode });
  },

  /**
   * 刷新令牌
   */
  refreshToken: (data: RefreshTokenRequest): Promise<AuthLoginResponse> => {
    return api_auth.post('refreshToken', '/system/api/v3/sys/auth/refresh', data);
  },

  /**
   * 租户用户刷新令牌
   */
  tenantRefreshToken: (data: RefreshTokenRequest & { tenantCode: string }): Promise<AuthLoginResponse> => {
    return api_auth.post('tenantRefreshToken', '/system/api/v3/tenant/auth/refresh', data);
  },

  /**
   * 获取当前用户信息
   */
  getCurrentUser: (): Promise<User> => {
    return api_auth.get('getCurrentUser', '/system/api/v3/sys/auth/current-user');
  },

  /**
   * 获取租户用户信息
   */
  getTenantUser: (tenantCode: string): Promise<User> => {
    return api_auth.get('getTenantUser', `/system/api/v3/tenant/auth/current-user/${tenantCode}`);
  },

  /**
   * 验证令牌有效性
   */
  validateToken: (token: string): Promise<{ valid: boolean }> => {
    return api_auth.get('validateToken', '/system/api/v3/sys/auth/validate', {
      params: { token }
    });
  },

  /**
   * 验证租户令牌有效性
   */
  validateTenantToken: (token: string, tenantCode: string): Promise<{ valid: boolean }> => {
    return api_auth.get('validateTenantToken', '/system/api/v3/tenant/auth/validate', {
      params: { token, tenantCode }
    });
  },

  // ===== RBAC权限管理 API =====
  
  /**
   * 获取用户权限信息
   */
  getUserPermissions: (userId: string, tenantCode?: string): Promise<{
    permissions: Permission[];
    roles: Role[];
    teams: Team[];
    departments: Department[];
  }> => {
    const endpoint = tenantCode 
      ? `/system/api/v3/tenant/user-permission/permissions/${userId}?tenantCode=${tenantCode}`
      : `/system/api/v3/sys/user-permission/permissions/${userId}`;
    return api_auth.get('getUserPermissions', endpoint);
  },

  /**
   * 获取租户用户权限信息
   */
  getTenantUserPermissions: (userId: string, tenantCode: string): Promise<{
    permissions: Permission[];
    roles: Role[];
    teams: Team[];
    departments: Department[];
  }> => {
    return api_auth.get('getTenantUserPermissions', `/system/api/v3/tenant/user-permission/permissions/${userId}/${tenantCode}`);
  },

  /**
   * 验证用户权限
   */
  checkPermission: (data: {
    userId: string;
    permissionCode: string;
    context?: any;
    tenantCode?: string;
  }): Promise<{ hasPermission: boolean; reason?: string }> => {
    const endpoint = data.tenantCode 
      ? '/system/api/v3/tenant/user-permission/check'
      : '/system/api/v3/sys/user-permission/check';
    return api_auth.post('checkPermission', endpoint, data);
  },

  /**
   * 验证租户用户权限
   */
  checkTenantPermission: (data: {
    userId: string;
    permissionCode: string;
    tenantCode: string;
    context?: any;
  }): Promise<{ hasPermission: boolean; reason?: string }> => {
    return api_auth.post('checkTenantPermission', '/system/api/v3/tenant/user-permission/check', data);
  },

  /**
   * 批量验证权限
   */
  checkPermissions: (data: {
    userId: string;
    permissions: string[];
    context?: any;
    tenantCode?: string;
  }): Promise<Record<string, boolean>> => {
    const endpoint = data.tenantCode 
      ? '/system/api/v3/tenant/user-permission/batch-check'
      : '/system/api/v3/sys/user-permission/batch-check';
    return api_auth.post('checkPermissions', endpoint, data);
  },

  /**
   * 批量验证租户用户权限
   */
  checkTenantPermissions: (data: {
    userId: string;
    permissions: string[];
    tenantCode: string;
    context?: any;
  }): Promise<Record<string, boolean>> => {
    return api_auth.post('checkTenantPermissions', '/system/api/v3/tenant/user-permission/batch-check', data);
  },

  /**
   * 验证用户角色
   */
  checkRole: (data: {
    userId: string;
    roleCode: string;
    tenantCode?: string;
  }): Promise<{ hasRole: boolean }> => {
    const endpoint = data.tenantCode 
      ? '/system/api/v3/tenant/user-permission/check-role'
      : '/system/api/v3/sys/user-permission/check-role';
    return api_auth.post('checkRole', endpoint, data);
  },

  /**
   * 验证租户用户角色
   */
  checkTenantRole: (data: {
    userId: string;
    roleCode: string;
    tenantCode: string;
  }): Promise<{ hasRole: boolean }> => {
    return api_auth.post('checkTenantRole', '/system/api/v3/tenant/user-permission/check-role', data);
  },

  /**
   * 获取用户可访问的菜单
   */
  getUserMenus: (userId: string, tenantCode?: string): Promise<any[]> => {
    const endpoint = tenantCode 
      ? `/system/api/v3/tenant/user-permission/menus/${userId}?tenantCode=${tenantCode}`
      : `/system/api/v3/sys/user-permission/menus/${userId}`;
    return api_auth.get('getUserMenus', endpoint);
  },

  /**
   * 获取租户用户可访问的菜单
   */
  getTenantUserMenus: (userId: string, tenantCode: string): Promise<any[]> => {
    return api_auth.get('getTenantUserMenus', `/system/api/v3/tenant/user-permission/menus/${userId}/${tenantCode}`);
  },

  /**
   * 获取用户在组织下的权限
   */
  getUserOrgPermissions: (data: {
    userId: string;
    orgId: string;
    includeInherited?: boolean;
  }): Promise<Permission[]> => {
    return api_auth.post('getUserOrgPermissions', '/system/api/v3/sys/user-permission/org-permissions', data);
  },

  /**
   * 计算用户综合权限（前端辅助功能）
   */
  calculateUserPermissions: (userId: string): Promise<{
    directRoles: Role[];
    teamRoles: Role[];
    allRoles: Role[];
    allPermissions: Permission[];
    accessibleMenus: any[];
  }> => {
    return api_auth.get('calculateUserPermissions', `/system/api/v3/sys/user-permission/calculate/${userId}`);
  },

  /**
   * 简化的权限检查（兼容现有代码）
   */
  hasPermission: async (userId: string, permissionCode: string, context?: any, tenantCode?: string): Promise<boolean> => {
    const result = await authApi.checkPermission({ userId, permissionCode, context, tenantCode });
    return result.hasPermission;
  },

  /**
   * 简化的角色检查（兼容现有代码）
   */
  hasRole: async (userId: string, roleCode: string, tenantCode?: string): Promise<boolean> => {
    const result = await authApi.checkRole({ userId, roleCode, tenantCode });
    return result.hasRole;
  },

  /**
   * 简化的租户权限检查
   */
  hasTenantPermission: async (userId: string, permissionCode: string, tenantCode: string, context?: any): Promise<boolean> => {
    const result = await authApi.checkTenantPermission({ userId, permissionCode, tenantCode, context });
    return result.hasPermission;
  },

  /**
   * 简化的租户角色检查
   */
  hasTenantRole: async (userId: string, roleCode: string, tenantCode: string): Promise<boolean> => {
    const result = await authApi.checkTenantRole({ userId, roleCode, tenantCode });
    return result.hasRole;
  },
};